/*
 * @Author: chunlai
 * @Date: 2023-12-22 16:47:19
 * @LastEditTime: 2025-08-06 16:24:39
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\translate\validate\fileds.js
 * @Description:投保常规必填字段校验
 */
import { userAge } from "@/methods/globals.js";
import { getDetailBirthDay } from "@/methods/date.js";
import { findPostCode } from "@/utils/GetPostcode.js";
import { createResult } from "@/translate/validate/customer.js";
import insuranceRules from "@/methods/occup.js";
import constantRules from "@/methods/rules.js";
import { getCacheValue } from "@/methods/cache.js";

const baosiName = getCacheValue("insert", "compEngName");
const validphone = /^1[3456789]\d{9}$/;
// 身高、体重、BMI
export const bmiRuleCheck = (userInfo, utype = "") => {
  if (userInfo.height === "") {
    return createResult(false, `请输入身高`, "height");
  }
  if (userInfo.weight === "") {
    return createResult(false, `请输入体重`, "weight");
  }
  if (isToCheck(userInfo, utype)) {
    if (userInfo.height > 240 || userInfo.height < 20) {
      return createResult(false, `身高输入错误，请确认`, "height");
    }
    if (userInfo.weight > 240 || userInfo.weight < 2) {
      return createResult(false, `体重输入错误，请确认`, "weight");
    }
  }
  return createResult(true);
};
export const isToCheck = (userInfo, userType = "") => {
  let res = true;
  // if (userType == "投保人" && userInfo.relationToAppnt == "4") {
  //   res = true;
  // }
  // if (userType == "被保人" && userInfo.relationToAppnt != "4") {
  //   res = true;
  // }
  if (userType == "受益人") {
    res = false;
  }
  return res;
};
// 证件类型
export const idTypeRuleCheck = (userInfo) => {
  if (userInfo.idType === "") {
    return createResult(false, `请选择证件类型`, "idType");
  }
  const ageVal = userAge(userInfo.birthDate);
  if (userInfo.idType === "3") {
    if (ageVal >= 16) {
      return createResult(false, `年满16周岁必须使用身份证`, "idType");
    }
  }
  if (userInfo.idType === "11") {
    let gapAge = 3;
    if (baosiName == "hezhong") {
      gapAge = 4;
    }
    // 0-2周岁（不含）可以使用出生证，0-16不含可以使用户口本
    else if (baosiName == "lian") {
      gapAge = 2;
    }
    if (ageVal >= gapAge) {
      return createResult(false, `年满${gapAge}周岁不能使用出生证`, "idType");
    }
  }
  return createResult(true);
};
// 证件有效期起期
export const validDateRuleCheck = (userInfo) => {
  if (baosiName == "hezhong" && userInfo.idType != "0") {
    return createResult(true);
  }
  if (userInfo.validDate === "") {
    return createResult(false, `请选择证件有效日期起期`, "validDate");
  }
  return createResult(true);
};
// 国籍
export const guojiRuleCheck = (userInfo) => {
  // console.log("---", constantRules);
  const guoji = userInfo.nationality.trim();
  if (guoji === "") {
    return createResult(false, `请选择国籍`, "nationality");
  }
  const configItem = constantRules.GuoJi;
  if (configItem[guoji]) {
    const gjItem = configItem[guoji],
      allowCfg = gjItem.allowedIdTypes,
      forbidCfg = gjItem.forbiddenIdTypes;
    if (allowCfg && !allowCfg.includes(userInfo.idType)) {
      return createResult(false, gjItem.message, "nationality");
    }
    if (forbidCfg && forbidCfg.includes(userInfo.idType)) {
      return createResult(false, gjItem.message, "nationality");
    }
  } else {
    if (!constantRules.GuoJi.OTHER.allowedIdTypes.includes(userInfo.idType)) {
      return createResult(
        false,
        constantRules.GuoJi.OTHER.message,
        "nationality"
      );
    }
  }
  return createResult(true);
};
// 职业
export const occupRuleCheck = (userInfo, userType = "") => {
  const { occupationCode, occupationCodeName, occupationClass } = userInfo;
  if (!occupationCode || !occupationCodeName) {
    return createResult(false, `请选择职业`, "occupationCode");
  }
  // 限制级(非本人,校验被保人)
  if (isToCheck(userInfo, userType)) {
    const page3Store = getCacheValue("page");
    const zhiyeClass = Number(occupationClass),
      occuMin = Number(page3Store.occuDisLevelMin),
      occuRrr = page3Store.occuDisLevelArr || [];
    if (zhiyeClass >= occuMin) {
      return createResult(
        false,
        `职业：${zhiyeClass}类(含)以上拒保`,
        "occupationCode"
      );
    }
    if (occuRrr.length > 0 && occuRrr.includes(zhiyeClass)) {
      return createResult(false, `职业${zhiyeClass}类：拒保`, "occupationCode");
    }
    const ruleFunc = insuranceRules.zhiyeRules[baosiName];
    // console.log(ruleFunc);
    if (ruleFunc) {
      const result = ruleFunc(userInfo);
      if (result) return result; // 如果规则校验失败，直接返回结果
    }
  }
  return createResult(true);
};
// 手机号
export const phoneRuleCheck = (userInfo) => {
  let obj = {
    msg: "",
    status: true,
    target: "phone",
  };
  if (userInfo.phone == "") {
    obj.msg = `请输入手机号`;
    obj.status = false;
    return obj;
  }
  if (!validphone.test(userInfo.phone)) {
    obj.msg = `手机号错误`;
    obj.status = false;
    return obj;
  }
  if (["lian"].includes(baosiName)) {
    const validLian = /(\d)\1{6}/;
    if (validLian.test(userInfo.phone)) {
      obj.msg = `手机号不得有7位连续重复数字`;
      obj.status = false;
      return obj;
    }
  }
  return obj;
};
// 兼职
export const partTimeJobCheck = (userInfo) => {
  let obj = {
    msg: "",
    status: true,
    target: "partTimeJob",
  };
  if (userInfo.partTimeJob === "") {
    obj.msg = `请输入兼职，没有请填“无”`;
    obj.status = false;
    return obj;
  }
  return obj;
};
// 税收文件填写
export const writeRevenueFileCheck = (userInfo, crsIdType, rInfo) => {
  let obj = {
    msg: "",
    status: true,
    target: "crsIdType",
  };
  if (baosiName === "fuxing") {
    // 税收居民类型选为1，且投保人证件类型为：护照（非大陆）、港澳通行证、台湾通行证时，需要填写税收居民身份声明的详细信息
    const test1 =
      ["1", "6", "7", "8"].includes(userInfo.idType) && crsIdType == "0";
    const test2 = crsIdType != "0";
    // console.log("0---", crsIdType);
    if (crsIdType == "" || crsIdType == undefined) {
      obj.msg = `请选择税收居民类型`;
      obj.status = false;
      return obj;
    }
    // console.log("1---", test1, test2);
    if (test1 || test2) {
      if (
        !rInfo.crsSurName ||
        !rInfo.crsName ||
        !rInfo.crsHomeNativePlace ||
        !rInfo.crsHomeAddress ||
        !rInfo.crsBirthNativePlace ||
        !rInfo.crsBirthAddress
      ) {
        obj.msg = `请填写税收居民身份声明的详细信息`;
      }
      if (obj.msg) {
        obj.status = false;
        return obj;
      }
    }
  }
  return obj;
};
// 工作单位
export const grpNameCheck = (userInfo, userType = "") => {
  if (userType.indexOf("被保人") != -1 && ["lian"].includes(baosiName)) {
    const cfgAge = getCacheValue("page", "minorAge");
    const minorAge = cfgAge || 18;
    if (userAge(userInfo.birthDate) < minorAge) {
      return createResult(true);
    }
  }
  if (userInfo.grpName === "") {
    return createResult(false, `请输入工作单位名称`, "grpName");
  }
  return createResult(true);
};
// 性别
export const sexRuleCheck = (userInfo, userType = "") => {
  let obj = {
    msg: "",
    status: true,
    target: "sex",
  };
  // console.log(userInfo.sex)
  if (userInfo.sex === "") {
    obj.msg = `请选择性别`;
    obj.status = false;
    return obj;
  }
  let insuSex = `${userInfo.sex}`;
  // 被保人与投保人之间的性别关系 校验
  if (userType == "被保人") {
    obj.target = "relationToAppnt";
    let tbrObj = getCacheValue("insert", "applicant") || {},
      tbrSex = `${tbrObj.sex}`;
    if (
      ["59", "0"].includes(`${userInfo.relationToAppnt}`) &&
      tbrSex == insuSex
    ) {
      return createResult(false, `与投保人性别相同，请修改关系`, "sex");
    }
  }
  // 限制性别投保 --- 待定
  const rage3Rule = getCacheValue("infoReg", "ageRange");
  const tbr2Obj = rage3Rule.applicant || {},
    bbr2Obj = rage3Rule.insured || {};
  let insurRule = userType == "投保人" ? tbr2Obj : bbr2Obj;
  if (insurRule.sexFixed != void 0) {
    if (insurRule.sexFixed !== insuSex) {
      obj.msg = `该产品仅限${
        insurRule.sexFixed == 1 ? "女性" : "男性"
      }可投保，请确认投保信息`;
      obj.status = false;
      if (["0", "3"].includes(userInfo.idType)) {
        obj.target = "relationship";
      }
      return obj;
    }
  }

  return obj;
};
// 生日
export const birthDayRuleCheck = (userInfo, userType = "") => {
  let obj = {
    msg: "",
    status: true,
    target: "birthDate",
  };
  if (userInfo.birthDate === "") {
    obj.msg = `请选择出生日期`;
    obj.status = false;
    return obj;
  }
  // 本人,只校验投保人
  if (userType.indexOf("投保人") != -1 || userType.indexOf("被保人") != -1) {
    obj = insAgeValide(userInfo, userType);
    if (!obj.status) return obj;
  }
  // 险种
  if (userType.indexOf("被保人") != -1) {
    obj = riskValide(userInfo);
    if (!obj.status) return obj;
  }
  return obj;
};

export const insAgeValide = (userInfo, userType = "") => {
  let obj = {
    msg: "",
    status: true,
    target: "birthDate",
  };
  const rage3Rule = getCacheValue("infoReg", "ageRange");
  let ageInsRule = rage3Rule.insured;
  if (userType == "投保人") {
    ageInsRule = rage3Rule.applicant;
  }
  // if (userType.indexOf("被保人") != -1 && userInfo.relationToAppnt == "4") {
  // ageInsRule.minAge = tbrAgeRule.minAge;
  // ageInsRule.isDate = false;
  // }
  // console.log("2---", userType, ageInsRule);
  const ruleMax = ageInsRule.maxAge,
    ruleMin = ageInsRule.minAge;
  const appliAge = userAge(userInfo.birthDate);
  if (["0", "3"].includes(userInfo.idType)) {
    obj.target = "idNum";
  }
  if (ageInsRule.isDate) {
    // 计算天数
    if (appliAge > ruleMax || getDetailBirthDay(userInfo.birthDate) < ruleMin) {
      obj.msg = `年龄需在${ruleMin}天到${ruleMax}岁之间`;
      obj.status = false;
      return obj;
    }
  } else {
    if (appliAge > ruleMax || appliAge < ruleMin) {
      obj.msg = `年龄需在${ruleMin}岁到${ruleMax}岁之间`;
      obj.status = false;
      return obj;
    }
  }
  return obj;
};
export const riskValide = (userInfo) => {
  let obj = {
    msg: "",
    status: true,
    target: "birthDate",
  };
  const appliAge = userAge(userInfo.birthDate);
  // 主险性别限制年龄校验规则(长城/00369)
  const riskReg = getCacheValue("risks"),
    zhuRisk = riskReg.find((ele) => ele.ismain),
    ruleCfg = zhuRisk.rules || [],
    ruleObj = ruleCfg.find((ele) => ele.type == "sexLimitMaxAge");
  // console.log('sexLimitMaxAge', ruleObj);
  if (ruleObj) {
    const usex = userInfo.sex,
      errStr = `${usex == "1" ? "女性" : "男性"}`,
      cfgObj = ruleObj.config.find((ele) => ele.sex == usex);
    if (cfgObj) {
      if (cfgObj.max && appliAge > cfgObj.max) {
        obj.msg = `${errStr}最大投保年龄为${cfgObj.max}岁`;
        obj.status = false;
        return obj;
      }
      if (cfgObj.min && appliAge < cfgObj.min) {
        obj.msg = `${errStr}最小投保年龄为${cfgObj.min}岁`;
        obj.status = false;
        return obj;
      }
    }
  }
  return obj;
};
// 邮编
export const zipCodeRuleCheck = (userInfo) => {
  // console.log("zipCodeRuleCheck");
  let obj = {
    msg: "",
    status: true,
    target: "zipCode",
  };
  if (!userInfo.zipCode) {
    obj.msg = `请输入邮编`;
    obj.status = false;
    return obj;
  }
  // console.log("1---", userInfo);
  if (userInfo.provinceName) {
    let postCode1 = findPostCode(
      userInfo.provinceName,
      userInfo.cityName,
      userInfo.countyName
    );
    if (postCode1) {
      if (postCode1.substring(0, 2) != userInfo.zipCode.substring(0, 2)) {
        obj.msg = `现居地邮编不符合,请确认`;
        // obj.status = false;
        return obj;
      }
    }
  }
  return obj;
};

// 亲属关系
export const insrRelaToTbr = (ageVal, relaValue) => {
  let obj = {
    target: "relationToAppnt",
    msg: "",
    status: true,
  };
  if (!["62", "45", "2"].includes(relaValue)) {
    // 1. 8周岁以下
    if (ageVal < 8) {
      obj.msg = "被保人8周岁以下和投保人的关系只能是子女";
      obj.status = false;
      return obj;
    }
    if (ageVal >= 8 && ageVal < 18) {
      const jinqin = ["35", "12", "69", "37"];
      if (!jinqin.includes(relaValue)) {
        obj.msg =
          "被保人8周岁以上和投保人的关系只能是子女或近亲属(孙子/女、外孙子/女、侄子/女、兄弟姐妹)";
        obj.status = false;
        return obj;
      } else {
        obj.breakTips =
          "被保人8周岁以上和投保人的关系非子女且为近亲属(孙子/女、外孙子/女、侄子/女、兄弟姐妹)";
        obj.status = true;
      }
    }
  }
  return obj;
};

// export const funName = (userInfo, userType) => {};
// isToCheck(userInfo, userType)
